//
//  UserInfoViewController.swift
//  NDAi
//
//  Created by 丸子 on 2024/7/1.
//

import UIKit
import TZImagePickerController

class UserInfoViewController: BaseViewController {
    let disposeBag = DisposeBag()
    let viewModel = UserInfoViewModel()
    var dataSource: [CellDataSource] = {
        let avatar = CellDataSource(tag: "info_avatar", title: "", imageName: "", cellType: UserInfoTableViewCell.self)
        let nickName = CellDataSource(tag: "info_nickname", title: "用户名", imageName: "", cellType: UserInfoTableViewCell.self)
        let userId = CellDataSource(tag: "info_userid", title: "用户ID", imageName: "", cellType: UserInfoTableViewCell.self)
        let loginChannel = CellDataSource(tag: "info_channel", title: "注册渠道", imageName: "", cellType: UserInfoTableViewCell.self)
        return [avatar, nickName, userId, loginChannel]
    }()
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = UITableView.automaticDimension
        tableView.register(cellWithClass: UserInfoTableViewCell.self)
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.contentInsetAdjustmentBehavior = .never
        return tableView
    }()
    
    private lazy var logoutBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleForNormal = "退出登录"
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
        button.backgroundColor = UIColor(hexString: "#25262B")
        button.allRound(22)
        return button
    }()
    
    private lazy var deleteBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleForNormal = "删除账号"
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
        button.backgroundColor = UIColor(hexString: "#CCCCCC")
        button.titleColorForNormal = .white
        button.allRound(22)
        return button
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(hexString: "#F3F2F7")
        
        self.navigationItem.title = "个人中心"
        self.view.addSubviews([tableView, logoutBtn, self.deleteBtn])
        
        tableView.snp.makeConstraints { make in
            make.top.equalTo(self.safeTop)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(self.deleteBtn.snp.top).offset(10)
        }
        
        deleteBtn.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(24)
            make.height.equalTo(44)
            make.bottom.equalTo(logoutBtn.snp.top).offset(-10)
        }
        
        logoutBtn.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(24)
            make.height.equalTo(44)
            make.bottom.equalTo(self.safeBottom).offset(-10)
        }
        
        logoutBtn.setClosureTouchUpInside_k { [weak self] in
            self?.logout()
        }
      
        viewModel.uploadDoneSubject.subscribe(onNext: { [weak self] _ in
            self?.tableView.reloadData()
        }).disposed(by: disposeBag)
        
        viewModel.okSubject.subscribe(onNext: { [weak self] _ in
            self?.navigationController?.popViewController(animated: true)
        }).disposed(by: disposeBag)
        
        
//        let rightBtn = UIButton(type: .custom)
//        rightBtn.setTitle("提交", for: .normal)
//        rightBtn.titleColorForNormal = .white
//        rightBtn.allRound(12)
//        rightBtn.titleLabel?.font = UIFont.pingFangSCRegular(ofSize: 15)
//        let rightItem = UIBarButtonItem(customView: rightBtn)
//        self.navigationItem.rightBarButtonItem = rightItem
//        rightBtn.setClosureTouchUpInside_k { [weak self] in
//            self?.view.endEditing(true)
//            self?.viewModel.uploadUserInfo()
//        }
        
        deleteBtn.setClosureTouchUpInside_k {
            self.deleteAccout()
        }
        
        viewModel.getData()
        self.tableView.reloadData()
    }
    
    func deleteAccout(){ 
        let popView = TipsPOPView()
        Appearance.addViewToWindow(popView)
        popView.initViews(title: "提示", desc: "你确定你要删除您的账户吗？删除后将无法恢复数据", style: .delete)
        popView.chooseDone = { [weak self] in
            self?.deleteE()
        }
    }
    
    func deleteE(){
        NDProgressHUD.showLoading()
        RequestService.instance.deleteUser(completeClosure: { [weak self] in
            NDProgressHUD.showSuccess(title: "", subtitle: "删除成功")
            self?.logout()
        }, failureClosure: { err in
            NDProgressHUD.showError(title: "", subtitle: err ?? "删除失败")
        })
    }
    
    func logout(){
        self.navigationController?.popViewController(animated: true)
        SqlManager.shared.delete(from: AccountModel.self)
        Appearance.shared.accoutModel = nil
        NDProgressHUD.showSuccess(title: "提示", subtitle: "退出登录成功")
    }
}

extension UserInfoViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data = dataSource[indexPath.item]
        guard let cell = tableView.dequeueReusableCell(withClass: data.cellType) as? UserInfoTableViewCell else {
            return UITableViewCell()
        }
        // 获取用户数据
        if let userData = Appearance.shared.accoutModel {
            // 判断是否为特定类型的单元格
            let isAvatarCell = (data.tag == "info_avatar")
            let isMailCell = (data.tag == "info_channel")
            let isNickNameCell = (data.tag == "info_nickname")
            let isUserId = (data.tag == "info_userid")
            // 如果是头像单元格，设置头像
            if isAvatarCell {
                if let icon = userData.userOtherInfo?.icon, let url = URL(string: icon) {
                    cell.avatarIV.sd_setImage(with: url, placeholderImage: UIImage(named: "icon_login_a"))
                } else {
                    cell.avatarIV.image = UIImage(named: "icon_login_a")
                }
            } else {
                cell.titleLb.text = data.title
            }
            // 如果是邮件或昵称单元格，设置文本字段
            if isNickNameCell {
                cell.textField.isEnabled = !isNickNameCell
                cell.textField.text = userData.userOtherInfo?.nickname ?? userData.userOtherInfo?.email ?? ""
                cell.textField.attributedPlaceholder =  NSAttributedString.init(string: "你的AI", attributes: [NSAttributedString.Key.font: UIFont.pingFangSCRegular(ofSize: 14),NSAttributedString.Key.foregroundColor:Theme.color.text_d1])
            }
            if isUserId {
                cell.textField.isEnabled = isNickNameCell
                cell.textField.text = "\(userData.userId ?? 0)"
            }
            
            if isMailCell {
                cell.textField.isEnabled = isNickNameCell
                cell.textField.text = userData.userOtherInfo?.customer_reg_source ?? userData.userOtherInfo?.app_channel ?? ""
            }
            // 根据单元格类型，显示或隐藏某些视图
            cell.avatarIV.isHidden = !isAvatarCell
            cell.titleLb.isHidden = isAvatarCell
            cell.textField.isHidden = isAvatarCell
            if isNickNameCell {
                cell.endInputClosure = { [weak self] text in
                    self?.viewModel.nickName = text ?? ""
                }
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.item == 0 {
//            self.presentPickerImage()
        }
    }
    
    private func presentPickerImage() {
        let picker = TZImagePickerController(maxImagesCount: 1, delegate: nil)
        picker?.modalPresentationStyle = .fullScreen
        picker?.allowPickingImage = true
        picker?.allowTakePicture = true
        picker?.allowPickingVideo = false
        picker?.allowTakeVideo = false
        picker?.allowCrop = true
        picker?.cropRect = CGRect(center: CGPoint(x: SCREEN_WIDTH / 2, y: SCREEN_HEIGHT / 2), size: CGSize(width: SCREEN_WIDTH, height: SCREEN_WIDTH))
        picker?.didFinishPickingPhotosHandle = { [weak self] images, anies, b in
            let image = images?.first
            self?.viewModel.uploadAvatar(image)
        }
        present(picker!, animated: true)
    }
}
